
from django.http import HttpResponse
from django.shortcuts import render_to_response, get_object_or_404
from django.template import RequestContext
from models import Status
import urllib2  
from lxml import html
import threading
import re
import socket
from datetime import datetime
from django.contrib.auth.models import User

lang_list = ["C","C++","Pascal","Java","Ruby","Bash","Python","PHP","Perl","C#","Other Language"];

sePattern = re.compile(r'top=(?P<top>-?\d+)&prevtop=(?P<prevtop>-?\d+)')
bitPattern = re.compile(r'^(\d+) B')

def update_test(test):
    url = "http://sdustoj.tk/contest.php?cid=" + test.contest_id
    while True:
        try:
            f = urllib2.urlopen(url, timeout=0.6)
            c = f.read()
        except socket.timeout:
            continue
        except urllib2.URLError:
            break
        doc = html.document_fromstring(c)
        con_stus = doc.xpath("//div[@id='main']/center/font[@color='red']")[0]
        if con_stus.text_content().find("Running") != -1:
            return            
        break
    
    test.status.all().delete()
    stus = []
    for cls in test.active.lesson.clses.all():
        stus.extend(cls.students.values_list('username', flat=True))
    pages = {'top':'a', 'prevtop':'b'}
    res = []
    link = "status.php?cid=%s" % (test.contest_id)
    
    while pages['top'] != pages['prevtop']:
        url = "http://sdustoj.tk/" + link
        try:
            f = urllib2.urlopen(url, timeout=0.6)
            c = f.read()
        except socket.timeout:
            continue
        except urllib2.URLError:
            break
        doc = html.document_fromstring(c)
        trs = doc.xpath("//table[@align='center']//tr[@align='center']")
        for tr in trs:
            user_id = tr[1].text_content()
            if user_id not in stus:
                continue
            status = Status(test=test,
                            s_id=tr[0].text_content(),
                            user_id=user_id,
                            prob_id=tr[2].text_content(),
                            )
            res_str = tr[3].text_content()
            result = -1
            if res_str == "Pending":
                resutl = 0
            elif res_str.find("Pending Rejudging") != -1:
                resutl = 1
            elif res_str.find("Compiling") != -1:
                result = 2
            elif res_str.find("Running & Judging") != -1:
                result = 3
            elif res_str.find("Accepted") != -1:
                result = 4
            elif res_str.find("Presentation Error") != -1:
                result = 5
            elif res_str.find("Wrong Answer") != -1:
                result = 6
            elif res_str.find("Time Limit Exceed") != -1:
                result = 7
            elif res_str.find("Memory Limit Exceed") != -1:
                result = 8
            elif res_str.find("Output Limit Exceed") != -1:
                result = 9
            elif res_str.find("Runtime Error") != -1:
                result = 10
            elif res_str.find("Compile Error") != -1:
                result = 11
            elif res_str.find("Compile OK") != -1:
                result = 12
            elif res_str.find("Invalid Word") != -1:
                result = 13
            status.result = result
            try:
                status.mem = int(tr[4].text_content())
            except ValueError:
                status.mem = 0
            try:
                status.time = int(tr[5].text_content())
            except ValueError:
                status.time = 0
            try:
                status.lang = lang_list.index(tr[6].text_content())
            except ValueError:
                status.lang = -1
            try:
                status.len = bitPattern.search(tr[7].text_content()).groups()[0]
            except IndexError:
                status.len = 0
            try:
                status.sub_time = datetime.strptime(tr[8].text_content(),"%Y-%m-%d %H:%M:%S")
            except ValueError:
                status.sub_time = datetime.now()
            status.save()
            res.append(status)
            
        a_elem = doc.xpath("//div[@id='main']/a")
        link = a_elem[2].attrib['href']
        pages = sePattern.search(link).groupdict()
    

def test_show(request, active):
    test = active.test
    if not test.status.count():
        update_test(test)
        #pass
    return render_to_response("content/active/active_detail.html", {'active':active}, context_instance=RequestContext(request))

active_show_func = {1:test_show}